<template>
  <CustomDialog
    ref="customDialogRef"
    class="pocket_card_detail"
    :before-close="beforeClose"
  >
    <div
      un-flex="~ [1_0_0] col basis-[inherit]"
      un-overflow-hidden
    >
      <div
        un-flex
        un-justify-center
        un-items-center
        un-p="y-2.5"
      >
        <el-button
          plain
          @click="cancelClk"
        >
          <template #icon>
            <ElIconCircleClose />
          </template>
          <span>取消</span>
        </el-button>

        <el-button
          plain
          type="primary"
          @click="saveClk"
        >
          <template #icon>
            <ElIconCircleCheck />
          </template>
          <span>确认</span>
        </el-button>

        <div
          v-if="ids && ids.length > 1"
          un-text="3 [var(--el-text-color-regular)]"
          un-absolute
          un-right-2
        >
          <el-button
            link
            :disabled="!dialogModel.id || ids.indexOf(dialogModel.id) <= 0"
            @click="prevIdClk"
          >
            上一项
          </el-button>

          <span>{{ ((dialogModel.id && ids.indexOf(dialogModel.id)) || 0) + 1 }} / {{ ids.length }}</span>

          <el-button
            link
            :disabled="!dialogModel.id || ids.indexOf(dialogModel.id) >= ids.length - 1"
            @click="nextIdClk"
          >
            下一项
          </el-button>

          <span v-if="changedIds.length > 0">
            {{ changedIds.length }}
          </span>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<script setup lang="ts">
const emit = defineEmits(['nextId'])

let inited = $ref(false)

let dialogAction = $ref('add')

let dialogModel = $ref<any>({})

let ids = $ref<string[]>([])
let changedIds = $ref<string[]>([])

let formRef = $ref<InstanceType<typeof ElForm> | undefined>()

/** 表单校验 */
let form_rules = $ref<Record<string, FormItemRule | FormItemRule[]>>({})

type OnCloseResolveType = {
  type: 'ok' | 'cancel'
  changedIds: string[]
}

let onCloseResolve = function (value: OnCloseResolveType) {}

/** 增加时的默认值 */
function getDefaultModel(): any {
  const defaultModel = {}
  return defaultModel
}

async function getSelectListEfc() {}

let customDialogRef = $ref<InstanceType<typeof CustomDialog>>()

/** 打开对话框 */
async function showDialog(arg?: {
  title?: string
  model?: {
    ids: string[]
  }
  action: 'add' | 'edit'
}) {
  inited = false
  const title = arg?.title
  const dialogRes = customDialogRef!.showDialog<OnCloseResolveType>({
    title
  })
  onCloseResolve = dialogRes.onCloseResolve
  formRef?.resetFields()
  const model = arg?.model
  const action = arg?.action
  dialogAction = action || 'add'
  ids = []
  changedIds = []
  dialogModel = {}
  await getSelectListEfc()
  if (action === 'add') {
    const defaultModel = await getDefaultModel()
    dialogModel = {
      ...defaultModel,
      ...model
    }
  } else if (action === 'edit') {
    ids = model?.ids ?? []
    if (ids && ids.length > 0) {
      dialogModel.id = ids[0]
      await refreshEfc()
    }
  }
  formRef?.clearValidate()
  inited = true
  return await dialogRes.dialogPrm
}

/** 刷新 */
async function refreshEfc() {
  formRef?.clearValidate()
  if (!dialogModel.id) {
    return
  }
  // const data = await detail(dialogModel.id);
}

/** 点击上一项 */
async function prevIdClk() {
  await prevId()
}

/** 点击下一项 */
async function nextIdClk() {
  await nextId()
}

/** 下一项 */
async function nextId() {
  if (!dialogModel.id) {
    if (ids && ids.length > 0) {
      dialogModel.id = ids[0]
    } else {
      return false
    }
  } else {
    const idx = ids.indexOf(dialogModel.id)
    if (idx >= 0 && idx < ids.length - 1) {
      dialogModel.id = ids[idx + 1]
    } else {
      return false
    }
  }
  await refreshEfc()
  emit('nextId', { dialogAction, id: dialogModel.id })
  return true
}

/** 上一项 */
async function prevId() {
  if (!dialogModel.id) {
    if (ids && ids.length > 0) {
      dialogModel.id = ids[0]
    }
  } else {
    const idx = ids.indexOf(dialogModel.id)
    if (idx > 0) {
      dialogModel.id = ids[idx - 1]
    } else {
      return false
    }
  }
  await refreshEfc()
  emit('nextId', { dialogAction, id: dialogModel.id })
  return true
}

/** 确定 */
async function saveClk() {
  try {
    await formRef?.validate()
  } catch (err) {
    return
  }

  // const isSucceed = await fetchResult()

  onCloseResolve({
    type: 'ok',
    changedIds
  })
}

/** 点击取消关闭按钮 */
function cancelClk() {
  onCloseResolve({
    type: 'cancel',
    changedIds
  })
}

async function beforeClose(done: (cancel: boolean) => void) {
  done(false)
  onCloseResolve({
    type: 'cancel',
    changedIds
  })
}

defineExpose({ showDialog })
</script>

<style lang="scss">
.pocket_card_detail.el-dialog {
  --el-dialog-width: auto;
  height: calc(100vh - 20px);
  .custom_dialog {
    width: auto;
    height: calc(100vh - 20px);
  }
  .card_type_active {
    border: 2px solid #1bb61a;
  }
}
</style>
